
//
//  AlertView.swift
//  BabaLink
//
//  Created by wrs on 2018/8/9.
//  Copyright © 2018年 wrs. All rights reserved.
//

import Foundation
import UIKit

open class AlertModel: NSObject {
    open var title: String?
    open var handle: (()->Void)?
    
    override init() {
        super.init()
    }

    public  convenience init(title: String?, handle: (() -> Void)?) {
        self.init()
        self.title = title
        self.handle = handle
    }
}

public func showActionSheet(title: String?, message: String?, modelArray: [AlertModel], cancelTitle: String?, cancelHandle: (()->Void)?, vc: UIViewController, sourceView: UIView?) -> Void {
    var cancelModel: AlertModel? = nil
    if let title = cancelTitle {
        cancelModel = AlertModel()
        cancelModel?.title = title
        cancelModel?.handle = cancelHandle
    }
    showAlertController(title: title, message: message, modelArray: modelArray, cancelModel: cancelModel, style: .actionSheet, vc: vc, sourceView: sourceView)
}

public func showAlert(title: String?, message: String?, modelArray: [AlertModel]?, cancelTitle: String?, cancelHandle: (()->Void)?, vc: UIViewController, sourceView: UIView?) -> Void {
    var cancelModel: AlertModel? = nil
    if let title = cancelTitle {
        cancelModel = AlertModel()
        cancelModel?.title = title
        cancelModel?.handle = cancelHandle
    }
    showAlertController(title: title, message: message, modelArray: modelArray, cancelModel: cancelModel, style: .alert, vc: vc, sourceView: sourceView)
}


fileprivate func showAlertController(title: String?, message: String?, modelArray: [AlertModel]?, cancelModel:AlertModel?, style: UIAlertController.Style, vc: UIViewController, sourceView: UIView?) -> Void {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: style)
    if let popver =  alertController.popoverPresentationController {
        var aSourceView = sourceView
        if aSourceView == nil {
            aSourceView = vc.view
        }
        popver.sourceView = aSourceView
        popver.sourceRect = aSourceView!.bounds
        popver.permittedArrowDirections = .any
    }
    if let tempModelArray = modelArray {
        for model in tempModelArray {
            let action =  UIAlertAction(title: model.title, style: .default) { (_) in
                if let handle = model.handle {
                    handle()
                }
            }
            alertController.addAction(action)
        }
    }
    if let cancel = cancelModel {
        let cancelAction =  UIAlertAction(title: cancel.title, style: .cancel) { (_) in
            if let handle = cancel.handle {
                handle()
            }
        }
        alertController.addAction(cancelAction)
    }
    vc.present(alertController, animated: true) {
        alertController.view.backgroundColor = UIColor.clear
    }
}
